var sysDic = {
    baseUrl: "/dic/sysDic",
    entity: "sysDic",
    currentItem: {},
};
var setting = {
		data: {
			simpleData: {
				enable: true,
				idKey: "dicId",
				pIdKey: "dicParentid",
				rootPId: "xxx",
			},
			key:{
				name:"dicName"
			}
		},
		callback: {
			beforeClick: function(treeId, treeNode) {
				$(".box-title").html(treeNode.dicName);
				//tablelist(treeNode.dicId);
				sysDic.currentItem = treeNode;
				dicTable.refresh();
			},
			onRightClick: function(treeId, treeNode) {
				$("#tree a").removeClass("curSelectedNode");
				$(".box-title").html("");
				sysDic.currentItem = {};
				dicTable.refresh();
			}
		}
};
sysDic.treeList=function(){
	$.ajax({
		type:"get",
		url:sysDic.baseUrl+"/tree",
		dataType:"json",
		contentType:"application/json",
		success:function(data){
			if(data.code=="200"){	
				var resultArr=data.data;	
				$.fn.zTree.init($("#tree"), setting, resultArr);
			}else{
				alert(data.message);
			}
		}
	})
}

//查询节点
function searchNodes(){  
    var treeObj = $.fn.zTree.getZTreeObj("tree");  
    var keywords=$("#btnSearch").val();  
    var nodes = treeObj.getNodesByParamFuzzy("dicName", keywords, null);  
    if (nodes.length>0) { 
        treeObj.selectNode(nodes[0]);  
    }
} 

/*function tablelist(id){
	$.ajax({
		type:"get",
		url:sysDic.baseUrl+"/"+id,
		dataType:"json",
		contentType:"application/json",
		success:function(data){
			if(data.code=="200"){
				if(data.data!=null && data.data.length){
					var resultArr=data.data;
					var html="";
					for(var i=0;i<resultArr.length;i++){
						var result = resultArr[i];
						if(result.dicDesc == null) result.dicDesc="";
						if(result.dicSort ==null) result.dicSort=""
						html+='<tr>';
						html+='<td class="text-center">' + (i+1)+ '</td>';						
						html+='<td>' + result.dicId + '</td>';						
						html+='<td>' + result.dicName + '</td>';
						html+='<td>' + result.dicSort + '</td>';
						html+='<td>' + result.dicDesc + '</td>';
						html+='</tr>';
					}
					$("#dictionary").html(html);
				}else{
					$("#dictionary").html("");
				}
			}else{
				alert(data.message);
			}
		}
	})
}*/

layui.use(['form', 'layedit', 'laydate'], function () {
	sysDic.treeList();
    var editIndex;
   // var layerTips = parent.layer === undefined ? layui.layer : parent.layer, //获取父窗口的layer对象
    var layerTips = layui.layer;
        layer = layui.layer, //获取当前窗口的layer对象
        form = layui.form,
        layedit = layui.layedit,
        laydate = layui.laydate;
    var addBoxIndex = -1;
    
    $('#btnAdd').on('click', function () {
        //本表单通过ajax加载 --以模板的形式，当然你也可以直接写在页面上读取
        $.get(sysDic.entity + '/add', null, function (form) {
            addBoxIndex = layer.open({
                type: 1,
                title: '添加字典',
                content: form,
                btn: ['保存', '取消'],
                shade: false,
                area: ['100%', '100%'],
                maxmin: false,
                yes: function (index) {
                    layedit.sync(editIndex);
                    //触发表单的提交事件
                    $('form.layui-form').find('button[lay-filter=add]').click();
                },
                full: function (elem) {
                    var win = window.top === window.self ? window : parent.window;
                    $(win).on('resize', function () {
                        var $this = $(this);
                        elem.width($this.width()).height($this.height()).css({
                            top: 0,
                            left: 0
                        });
                        elem.children('div.layui-layer-content').height($this.height() - 95);
                    });
                },
                success: function (layero, index) {
                	var form = layui.form;
                    form.render();//渲染视图
                    setFromValues(layero,sysDic.currentItem);
                    $("#plus").on('click',function(){
                    	var html='<tr><td class="text-center">子类</td>';
                    	html += '<td><input type="text" class="layui-input" name="id" placeholder="必填" lay-verify="required" /></td>';
                    	html +=	'<td><input class="layui-input" type="text" name="name" placeholder="必填" lay-verify="required"/></td>';
                    	html += '<td><input type="text" class="layui-input" name="sort" /></td>';
                    	html += '<td><input class="layui-input" type="text" name="desc" /></td>';
                    	html += '<td><input type="checkbox" value="1" name="is"/></td></tr>';
                    	$("#zL").append(html);
                    	form.render();
                    })                                   
                    form.on('submit(add)', function (data) {
                    	 var data0;
                    	 var classId="";
                    	 var pId = $("#dicId").val();
                         if(sysDic.currentItem.dicId ==null){
                         	data0 = [{
                     			"dicId":pId,
                     			"dicName":$("#dicName").val(),
                     			"dicParentid":"xxx",
                     			"dicDesc":"",
                     			"dicIsenable":"1",
                     			"isleaf":"1",
                     			"classId":"xxx"
                         	}];
                         	classId=$("#dicId").val();
                         }else{
                         	data0=[];
                         	$("#dicId").attr('disabled',true);
                         	$("#dicName").attr('disabled',true);
                         	classId=sysDic.currentItem.classId=="xxx"?pId:sysDic.currentItem.classId;
                         }
                    	
                    	$("#zL tr").each(function(){
                    		var id = $(this).find("[name=id]").val();
                    		var name = $(this).find("[name=name]").val();
                    		var sort = $(this).find("[name=sort]").val();
                    		var desc = $(this).find("[name=desc]").val();
                    	    var is = $(this).find("[name=is]:checked").val()=="1"?"1":"";
                	    	data0.push({
                	    		"dicId":id,
                	    		"dicName":name,
                	    		"dicSort":sort,
                	    		"dicDesc":desc,
                	    		"dicParentid":pId,
                	    		"isleaf":is,
                	    		"dicIsenable":"1",
                	    		"classId":classId
                	    	});
                    	});
                        $.ajax({
                            url: sysDic.baseUrl,
                            type: 'post',
                            dataType: "json",
                            contentType:"application/json",
                            data:JSON.stringify(data0),
                            success: function (data) {
                            	if(data.code=='200'){
	                                layerTips.msg('添加成功');
	                                layer.close(index);
	                                sysDic.treeList();
	                                dicTable.refresh();
                            	}else{
                            		layerTips.msg(data.message);
                            		layer.close(index);
	                                sysDic.treeList();
                            	}
                            }
                        });
                        //这里可以写ajax方法提交表单
                        return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
                    });
                },
                end: function () {
                    addBoxIndex = -1;
                }
            });
        });
    });    
    
    $('#btnEdit').on('click', function () {
    	var row ="";
    	var treeFlag=false;
        if (dicTable.select()) {
        	row = dicTable.currentItem;        	
        }else if(sysDic.currentItem.dicId){
        	row = sysDic.currentItem;
        	treeFlag=true;
        }else{
        	layerTips.msg("请选择要修改的数据！");
        }
        if(row){
            $.get(sysDic.entity + '/edit', null, function (form) {
                layer.open({
                    type: 1,
                    id:'sysDic',
                    title: '编辑菜单',
                    content: form,
                    btn: ['保存', '取消'],
                    shade: false,
                    area: ['100%', '100%'],
                    maxmin: true,
                    yes: function (index) {
                        layedit.sync(editIndex);
                        //触发表单的提交事件
                        $('form.layui-form').find('button[lay-filter=edit]').click();
                    },
                    full: function (elem) {
                        var win = window.top === window.self ? window : parent.window;
                        $(win).on('resize', function () {
                            var $this = $(this);
                            elem.width($this.width()).height($this.height()).css({
                                top: 0,
                                left: 0
                            });
                            elem.children('div.layui-layer-content').height($this.height() - 95);
                        });
                    },
                    success: function (layero, index) {
                        var form = layui.form;
                        setFromValues(layero, row);
                        editIndex = layedit.build('dicDesc');
                        //layero.find(":input[name='code']").attr("disabled", "");
                        if(treeFlag){
                        	$("#sort").hide();
                        }
                        form.render();
                        form.on('submit(edit)', function (data) {                     	
                            $.ajax({
                                url: sysDic.baseUrl,
                                type: 'put',
                                data: data.field,
                                dataType: "json",
                                success: function (data) {
                                	if(data.code=='200'){
                                		layerTips.msg('更新成功');
	                                    layer.close(index);
	                                    sysDic.treeList();
		                                dicTable.refresh();
	                                }else {
	                                    layerTips.msg(data.message);
	                                    layer.close(index);
	                                    //location.reload();
	                                }
                            	}

                            });
                            //这里可以写ajax方法提交表单
                            return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
                        });
                    }
                });
            });

        }
    });
    $('#btnDel').on('click', function () { 
        var data={};
        if(dicTable.select()){
        	data=JSON.stringify(dicTable.currentItem);
        }else if(sysDic.currentItem.dicId){
        	data=JSON.stringify(sysDic.currentItem);
        	$(".box-title").html("");
			sysDic.currentItem = {};
        }else{
        	layerTips.msg("请选择要删除的数据！");
        	return;
        }
        layer.confirm('确定删除数据吗？', null, function (index) {
            $.ajax({
                url: sysDic.baseUrl,
                type: "DELETE",
                data: data,
                dataType: "json",
                contentType:"application/json",
                success: function (data) {
                    if (data.code == '200') {
                        layerTips.msg("移除成功！");
                        sysDic.treeList();
                        dicTable.refresh();
                    } else {
                        layerTips.msg(data.message);
                    }
                }
            });
            layer.close(index);
        });
    })
    
    
  
});